#!/usr/bin/env python
# -*- coding: UTF-8 -*-

from contextlib import asynccontextmanager
import uvicorn
from fastapi import FastAPI, logger

from app import bootstrap
from app.config import globalAppSettings
import socket


def get_local_ip():
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    try:
        s.connect(("8.8.8.8", 80))
        ip = s.getsockname()[0]
    except Exception:
        ip = "127.0.0.1"
    finally:
        s.close()
    return ip


@asynccontextmanager
async def lifespan(server: FastAPI):
    # 启动时执行
    globalAppSettings.host_ip = get_local_ip()
    print(f"启动服务在IP: {globalAppSettings.host_ip}")
    yield  # 应用运行期间


# 实例化
server = FastAPI(
    redoc_url=None,
    docs_url="/doc",
    title=globalAppSettings.app_name,
    root_path="/api",
    lifespan=lifespan,
)
# 初始化项目
bootstrap.Init(server)


if __name__ == "__main__":
    print("打印项目配置:", globalAppSettings)

    # 使用 python main.py 启动服务
    uvicorn.run(
        server, host=globalAppSettings.app_host, port=globalAppSettings.app_port
    )
